/*捂脸猫FaceCat框架 v1.0
 1.创始人-矿洞程序员-上海宁米科技创始人-脉脉KOL-陶德 (微信号:suade1984);
 2.联合创始人-上海宁米科技创始人-袁立涛(微信号:wx627378127);
 3.联合创始人-河北思尔企业管理咨询有限公司合伙人-肖添龙(微信号:xiaotianlong_luu);
 4.联合开发者-陈晓阳(微信号:chenxiaoyangzxy)，助理-朱炜(微信号:cnnic_zhu);
 5.该框架开源协议为BSD，欢迎对我们的创业活动进行各种支持，欢迎更多开发者加入。
 包含C/C++,Java,C#,iOS,MacOS,Linux六个版本的图形和通讯服务框架。
 */
package facecat.topin.service;

import facecat.topin.core.*;
import facecat.topin.chart.*;

/**
 * 提示方法
 *
 */
public class CFunctionEx extends CFunction {

    /**
     * 创建方法
     *
     * @param indicator 指标
     * @param id ID
     * @param name 名称
     * @inative XML
     */
    public CFunctionEx(FCScript indicator, int id, String name, FCNative inative) {
        m_indicator = indicator;
        m_ID = id;
        m_name = name;
        m_native = inative;
    }

    /**
     * 指标
     *
     */
    public FCScript m_indicator;

    /**
     * XML对象
     *
     */
    public FCNative m_native;

    private static CVariable m_tempVariable;

    /**
     * 所有方�?
     *
     */
    private static final String FUNCTIONS = "CREATETHREAD,ISAPPALIVE";

    /**
     * 开始索引
     */
    private static final int STARTINDEX = 1000000;

    /**
     * 计算
     *
     * @param var 变量
     * @return 结果
     */
    @Override
    public double onCalculate(CVariable var) {
        switch (var.m_functionID) {
            case STARTINDEX:
                return CREATETHREAD(var);
            default:
                return 0;
        }
    }

    /**
     * 创建指标
     *
     * @param script 脚本
     * @param inative XML
     * @return 指标
     */
    public static FCScript createIndicator(String script, FCNative inative) {
        FCScript indicator = new FCScript();
        FCDataTable table = new FCDataTable();
        indicator.setDataSource(table);
        CFunctionBase.addFunctions(indicator);
        CFunctionHttp.addFunctions(indicator);
        int index = STARTINDEX;
        String[] functions = FUNCTIONS.split("[,]");
        int functionsSize = functions.length;
        for (int i = 0; i < functionsSize; i++) {
            indicator.addFunction(new CFunctionEx(indicator, index + i, functions[i], inative));
        }
        indicator.setScript(script);
        table.addColumn(0);
        table.set(0, 0, 0);
        indicator.onCalculate(0);
        return indicator;
    }

    private double CREATETHREAD(CVariable var) {
        m_tempVariable = var;
        Thread thread = new Thread() {
            public void run() {
                FCScript indicator = createIndicator(FCHttpMonitor.getMainMonitor().getScript(), m_native);
                indicator.callFunction(m_indicator.getText(m_tempVariable.m_parameters[0]));
                indicator.delete();
            }
        };
        thread.start();
        return 0;
    }
}
